package com.imarad.server.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author hhu 【huan.hu@cnambition.com】
 * @version com.imarad.server.bio, v 0.1 2018/2/1 11:54 hhu Exp $$
 */
public class BioServer implements Runnable {
    /**
     * 日志工具
     */
    private static final Logger LOG  = LoggerFactory.getLogger(BioServer.class);
    /**
     * 服务端口号
     */
    private int                 port = 8092;

    public BioServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        boolean isRun = true;
        try (ServerSocket serverSocket = new ServerSocket(this.port)) {
            LOG.info("BIO服务器启动成功,服务端口:{}", port);
            String key;
            Socket socket;
            while (isRun) {
                // 监听
                socket = serverSocket.accept();
                key = makeClientKey(socket);
                LOG.info("{}已经连入", key);
                new Thread(new BioServerHandler(socket, key)).start();
            }
        } catch (IOException e) {
            LOG.error("服务端异常", e);
        }
    }

    /**
     * 构造客户端key
     *
     * @return
     */
    private String makeClientKey(Socket socket) {
        String key;
        InetSocketAddress clientAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
        key = "Client[host=" + clientAddress.getHostName() + ", ip="
              + clientAddress.getAddress().getHostAddress() + ", port=" + clientAddress.getPort()
              + "]";
        if (StringUtils.isEmpty(key)) {
            key = "Client_" + System.nanoTime();
        }
        return key;
    }
}
